package com.example.chartgpt.service;

import com.example.chartgpt.model.Request;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

@Service
public class JsonServiceImp implements IJson{

    @Override
    public String JsontoString(String str) {

        //使用jackson库解析json
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(str);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String answer = jsonNode.get("choices").get(0)
                .get("message").get("content").asText();

        //TODO: 限制每次请求的最大token数,并将超出的token数分割成多个请求
//        int count = Integer.parseInt(jsonNode.get("usage").get("tokens").asText());
//        Integer maxTokens = new Request().getMax_tokens();
//        if (count > maxTokens){
//            //建立一个数组,将count分割成多个maxTokens
//        }
        return answer;
    }
}
